﻿using AutoMapper;
using B.S.Filtration.Domain.到货检验;
using B.S.Filtration.ErrorCode;
using B.S.Filtration.Read.Api.Application.Command.到货检验.BasicInfoCommand;
using MediatR;
using SqlSugar;

namespace B.S.Filtration.Read.Api.Application.CommandHander.到货检验.BasicInfoHandler
{
    public class GetBasicInfoHandler : IRequestHandler<GetBasicInfoCommand, APIResult<APIPaging<BasicInfo>>>
    {
        private readonly ISqlSugarClient db;
        private readonly IMapper mapper;
        public GetBasicInfoHandler(ISqlSugarClient db, IMapper mapper)
        {
            this.db = db;
            this.mapper = mapper;
        }
        public async Task<APIResult<APIPaging<BasicInfo>>> Handle(GetBasicInfoCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPaging<BasicInfo>> reat = new APIResult<APIPaging<BasicInfo>>();
            var listtt = await db.Queryable<BasicInfo>().Where(x => !x.IsDel).ToListAsync();


            if (!string.IsNullOrEmpty(request.InspectionSubject))
            {
                listtt = listtt.Where(x => x.InspectionSubject.Contains(request.InspectionSubject)).ToList();
            }
            if (!string.IsNullOrEmpty(request.InspectionOrderNumber))
            {
                listtt = listtt.Where(x => x.InspectionOrderNumber.Contains(request.InspectionOrderNumber)).ToList();
            }
            if (!string.IsNullOrEmpty(request.PurchaseOrderNumber))
            {
                listtt = listtt.Where(x => x.PurchaseOrderNumber.Contains(request.PurchaseOrderNumber)).ToList();
            }

            if (request.InspectionDate != null)
            {
                listtt = listtt.Where(x => x.InspectionDate.Date == request.InspectionDate.Value.Date).ToList();
            }
            if (request.PurchaseDate != null)
            {
                listtt = listtt.Where(x => x.PurchaseDate.Date == request.PurchaseDate.Value.Date).ToList();
            }

            int totalCount = listtt.Count();
            int PageCount = (int)Math.Ceiling(totalCount * 1.0 / request.pageSize);
            listtt = listtt.OrderByDescending(a => a.BasicInfoid).Skip((request.pageindex - 1) * request.pageSize).Take(request.pageSize).ToList();
            APIPaging<BasicInfo> paging = new APIPaging<BasicInfo>()
            {
                TotalCount = totalCount,
                TotalPage = PageCount,
                list = listtt.ToList(),
            };
            reat.code = APIResultCode.success;
            reat.msg = "显示成功";
            reat.data = paging;
            return reat;
        }
    }
}
